#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Kang.Cunhua
# @Date:   2015-12-30 15:30:21
# @Last Modified by:   Kang.Cunhua
# @Last Modified time: 2016-01-05 11:51:06
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait  # available since 2.4.0
import time
import logging
import logging.config

# 日志初始化
LOG_FILENAME = 'logging.conf'
logging.config.fileConfig(LOG_FILENAME)
logger = logging.getLogger('simple_log_example')


def login_system(driver, host):
    '''''
    登陆到全流程信贷系统
    '''

    # 如果要调用send_keys传递中文或特殊字符，需对字符串先 .decode('utf-8')；
    username = 'c0121100'
    password = 'passwordk'

    driver.get(host)

    driver.find_element_by_id("username").clear()
    driver.find_element_by_id("username").send_keys(username)
    driver.find_element_by_id("password").clear()
    driver.find_element_by_id("password").send_keys(password)
    # 执行JS直接提交 form
    driver.execute_script('document.forms[0].submit()')
    # 看源码是通过点击图片提交的，此处可如此模拟；
    # driver.find_element_by_id("submitButton").click()

    # 提交 form，这两种方式均调用不成功，或许与页面form代码有关
    # driver.find_element_by_id("loginForm").submit()
    # driver.find_elements_by_tag_name("form")[0].submit()

    try:
        # we have to wait for the page to refresh, the last thing that seems to be updated is the title
        WebDriverWait(driver, 10).until(lambda driver: driver.title.lower().startswith("国家"))

        # You should see "国家***"
        print driver.title
        print username, '巡检', 'host', 'login success！'
        logger.info(driver.title)
        logger.info('%s check %s loggin success!' % (username, host))

    finally:
        # driver.quit()
        print username, '巡检', 'host', 'login failed！'
        logger.info('%s check %s has checked!' % (username, host))

if __name__ == '__main__':
    driver = webdriver.Ie()
    login_url = ['http://10.29.132.20:9080/qlc/auth/login.jsp',
                 'http://10.29.132.20:9081/qlc/auth/login.jsp', 'http://10.29.132.20:9083/qlc/auth/login.jsp',
                 'http://10.29.132.22:9080/qlc/auth/login.jsp', 'http://10.29.132.22:9081/qlc/auth/login.jsp',
                 'http://10.29.132.22:9082/qlc/auth/login.jsp', 'http://10.29.132.22:9083/qlc/auth/login.jsp']
    for host in login_url:
        print 'try to login ', host
        logger.info('try to login %s!' % host)
        login_system(driver, host)
        time.sleep(0.5)
    driver.quit()

# 报错：
# UnicodeDecodeError: 'utf8' codec can't decode byte 0xe5 in position 0: unexpected end of data

# 处理：
# + values = values.decode('utf-8')
# + unicode(value, errors='ignore')
# + 在汉字前面加上u就可以解决这个问题
# + search.find_element_by_id("q_show").send_keys(u"中文")
